import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_web_test/pages/snake/SnakeWidget.dart';

import 'EventBus.dart';

enum ControllSign { left, top, right, bottom }

class SnakeHome extends StatefulWidget {
  SnakeHome({Key? key}) : super(key: key);
  var bus = EventBus();
  @override
  _SnakeHomeState createState() => _SnakeHomeState();
}

class _SnakeHomeState extends State<SnakeHome> {
  double _width = 0;
  bool loading = true;

  @override
  void initState() {
    super.initState();
    // 初始化宽高数据
    if (loading) {
      Future.delayed(Duration.zero, () {
        Size size = MediaQuery.of(context).size;
        var width = size.width - 40;
        _width = width > 350 ? 350 : width;
        setState(() {
          loading = false;
        });
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    if (loading) {
      return Scaffold(
        body: Center(child: Text('初始化...')),
      );
    }
    return Scaffold(
      body: Container(
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Padding(
                child: Text('贪吃蛇游戏'),
                padding: EdgeInsets.only(bottom: 20),
              ),
              Stack(
                children: [
                  //棋盘
                  Positioned(
                    child: Checker(columns: 20, size: Size(_width, _width)),
                  ),
                  // 游戏部分
                  Positioned(
                      child: SnakeWidget(
                    columns: 20,
                    width: _width,
                  )),
                ],
              ),
              SizedBox(height: 20,),
              ControllBlock(
                height: 200,
                width: 200,
                pressBottom: toBottom,
                pressLeft: toLeft,
                pressRight: toRight,
                pressTop: toTop,
              ),
              // 控制部分
              SizedBox(
                height: 300,
                width: 300,
                child: Column(
                  children: [
                    Padding(
                      padding: EdgeInsets.only(top: 20),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceAround,
                        children: [
                          ElevatedButton(
                            onPressed: () {
                              print('重置');
                              bus.emit('gameReset');
                            },
                            child: Text('重新开始'),
                          ),
                          ElevatedButton(
                            onPressed: () {
                              print('停止');
                              bus.emit('gameStop');
                            },
                            child: Text('停止'),
                          ),
                          ElevatedButton(
                            onPressed: () {
                              print('开始');
                              bus.emit('gameStart');
                            },
                            child: Text('开始'),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              )
            ],
          ),
        ),
      ),
    );
  }

  void toTop() {
    bus.emit('moveTo', ControllSign.top);
  }

  void toRight() {
    bus.emit('moveTo', ControllSign.right);
  }

  void toBottom() {
    bus.emit('moveTo', ControllSign.bottom);
  }

  void toLeft() {
    bus.emit('moveTo', ControllSign.left);
  }
}

///棋盘
class Checker extends StatelessWidget {
  Checker({Key? key, this.columns = 20, this.size}) : super(key: key);

  int columns;
  Size? size;

  @override
  Widget build(BuildContext context) {
    return Container(
      child: CustomPaint(
        size: size as Size,
        painter: CheckerPainter(columns),
      ),
    );
  }
}

///棋盘Painter
class CheckerPainter extends CustomPainter {
  CheckerPainter(this.columns);

  ///多少列
  final int columns;

  @override
  void paint(Canvas canvas, Size size) {
    double cellWidth = size.width / columns;
    // 绘制背景
    var paint = Paint()
      ..isAntiAlias = true
      ..style = PaintingStyle.fill
      ..color = Colors.yellow[200] as Color;
    canvas.drawRect(Offset.zero & size, paint);

    // 绘制线
    paint
      ..isAntiAlias = true
      ..style = PaintingStyle.stroke
      ..color = Colors.black54
      ..strokeWidth = 1;
    // 竖线
    for (var i = 0; i <= columns; i++) {
      canvas.drawLine(
          Offset(i * cellWidth, 0), Offset(i * cellWidth, size.height), paint);
    }
    // 横线
    for (var i = 0; i <= columns; i++) {
      canvas.drawLine(
          Offset(0, i * cellWidth), Offset(size.height, i * cellWidth), paint);
    }
  }

  @override
  bool shouldRepaint(CheckerPainter oldDelegate) => false;

  @override
  bool shouldRebuildSemantics(CheckerPainter oldDelegate) => false;
}

///控制部分
class ControllBlock extends StatelessWidget {
  ControllBlock(
      {Key? key,
      @required this.width = 0,
      @required this.height = 0,
      @required this.pressBottom,
      @required this.pressTop,
      @required this.pressLeft,
      @required this.pressRight})
      : super(key: key);

  double height;
  double width;
  Function? pressLeft;
  Function? pressTop;
  Function? pressBottom;
  Function? pressRight;

  @override
  Widget build(BuildContext context) {
    return ClipOval(
      child: Transform.rotate(
          angle: pi / 4,
          child: Container(
            color: Colors.grey[200],
            height: height,
            width: width,
            child: Column(
              children: [
                Expanded(
                  child: Row(
                    children: [setBtn('↑', pressTop), setBtn('→', pressRight)],
                  ),
                ),
                Expanded(
                  child: Row(
                    children: [
                      setBtn('←', pressLeft),
                      setBtn('↓', pressBottom)
                    ],
                  ),
                )
              ],
            ),
          )),
    );
  }

  Widget setBtn(String str, [Function? press]) {
    return Expanded(
      child: Center(
        child: SizedBox(
          width: double.infinity,
          height: double.infinity,
          child: TextButton(
            child: Transform.rotate(
              angle: -(pi / 4),
              child: Text(str, style: TextStyle(fontSize: 45)),
            ),
            onPressed: () {
              if (press != null) press();
            },
          ),
        ),
      ),
    );
  }
}
